<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

	function addPage() {
		var xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=function()
		  {
		  if (xmlhttp.readyState==4 && xmlhttp.status==200)
		    {
		    document.getElementById("mytest").innerHTML=xmlhttp.responseText;
		    }
		  }
		xmlhttp.open("POST","add_menu_page.php",true);
		xmlhttp.send();
		addNewPageLine();
	}

	function addNewPageLine() {
		var table=document.getElementById("pageTbl");
		var row=table.insertRow(-1);
		var cell1=row.insertCell(0);
		cell1.innerHTML="New";
	}
	
</script>
</head>
<body>

<?php

$con = mysqli_connect ( "localhost", "cms", "cms", "cms" );
if (mysqli_connect_errno ()) { // Check connection
	echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}

if ($_SERVER ['REQUEST_METHOD'] === 'POST') {
	
	$mid = $_POST[id];
	$name = $_POST[name];
	
	if ($mid) { // editing existing menu
		$sql = "UPDATE menu SET name = '$name' WHERE id='$mid'";
	} else {
		$sql = "INSERT INTO menu (name) VALUES ('$name')";
	}
	if (! mysqli_query ( $con, $sql )) {
		die ( 'Error: ' . mysqli_error ( $con ) );
	}
	echo "Menu saved";
} else {
	
	// get menu
	$mid = $_GET[id];
	$sql = "SELECT name FROM menu WHERE id = '$mid'";
	$result = mysqli_query ( $con, $sql );
	$row = mysqli_fetch_array ( $result );
	$name = $row[name];
	
	// available pages
	$sql_pages = "SELECT id, title FROM page";
	$pages = mysqli_query ( $con, $sql_pages );
	
	// menu-page-relations
	//$sql_rel = "SELECT id, page_id FROM menu_page WHERE menu_id = '$mid'";
	//$pages = mysqli_query ( $con, $sql_rel );
}

mysqli_close ( $con );

?>

		<form action="<?php if ($mid) 'edit_menu.php?id=' . $mid; else 'edit_menu.php'; ?>" method="post">
			<input hidden="true" name="id" value="<?php echo $mid; ?>" />
			
			<div>
				Name: <input type="text" name="name" value="<?php echo $name; ?>" />
			</div>
			<div>
				<input type="submit" value="Save">
			</div>
			
		</form>
		
		<div>
				<h2>Pages</h2>
				<table id="pageTbl">
					<tr>
						<th>Page</th>
					</tr>
					<tr>
						<td>
							<select>
								<option>...</option>
								<?php
									while ($page = mysqli_fetch_array ( $pages )) {
								?>
									<option><?php echo $page[title] ?></option>
								<?php
									}
								?>
							</select>
					</td>
					<td>
						<button onclick="addPage()">Add</a>
					</tr>
				</table>
			</div>
		
		<div>
			<textarea id="mytest" rows="10" cols="100"></textarea>
		</div>
	
	</body>
</html>
